/**
 * Copyright (c) 2018 昆明帮联传媒科技有限公司 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.framework.loippi.sms;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.framework.loippi.cache.ConfigCache;
import com.framework.loippi.service.RedisService;
import com.framework.loippi.utils.web.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * 阿里云短信服务
 *
 * @author Mark sunlightcs@gmail.com
 */
@Slf4j
@Service
public class AliyunSmsService extends AbstractSmsService {

    int SMS_CONFIG = 100003001;
    int MAIL_TEMPLATE_NOT_EXISTS = 100003002;
    int SEND_SMS_ERROR = 100003003;
    /**
     * 成功
     */
    public static final int SUCCESS = 1;
    /**
     * 失败
     */
    public static final int FAIL = 0;
    /**
     * OK
     */
    public static final  String OK = "OK";
    /**
     * 短信API产品名称（短信产品名固定，无需修改）
     */
    private final String PRODUCT = "Dysmsapi";
    /**
     * 短信API产品域名（接口地址固定，无需修改）
     */
    private final String DOMAIN = "dysmsapi.aliyuncs.com";

    private IClientProfile profile;


    public AliyunSmsService(){
        //初始化
        init();
    }




    private void init(){
        try {
            System.out.println("初始化阿里云短信");
            System.out.println(ConfigCache.getConfig("sms.aliyun.accessKeyId"));
            System.out.println(ConfigCache.getConfig("sms.aliyun.accessSecret"));
            //初始化acsClient，暂不支持region化
            profile = DefaultProfile.getProfile("cn-hangzhou",ConfigCache.getConfig("sms.aliyun.accessKeyId"),ConfigCache.getConfig("sms.aliyun.accessSecret"));
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", PRODUCT, DOMAIN);
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendSms(String mobile, LinkedHashMap<String, String> params) {
        this.sendSms(mobile, params,ConfigCache.getConfig("sms.aliyun.signName"),ConfigCache.getConfig("sms.aliyun.templateCode"));
    }


    @Override
    public void sendSms(String mobile, String code) {
        LinkedHashMap<String, String> params = new LinkedHashMap<>();
        params.put("code",code);
        this.sendSms(mobile, params,ConfigCache.getConfig("sms.aliyun.signName"),ConfigCache.getConfig("sms.aliyun.templateCode"));
    }

    public void sendSmsTools(String mobile, String smsKey){
        init();
        AliyunSmsService aliyunSmsService = SpringUtils.getBean("aliyunSmsService",AliyunSmsService.class);
        RedisService redisService = SpringUtils.getBean("redisServiceImpl", RedisService.class);

        String code = genCode();
        System.out.println("aliYunCode:" + code);
        aliyunSmsService.sendSms(mobile,code);
        redisService.save(smsKey, code,5*60);
    };

    @Override
    public void sendSms(String mobile, LinkedHashMap<String, String> params, String signName, String template) {
        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
        System.setProperty("sun.net.client.defaultReadTimeout", "30000");

        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        //待发送手机号，支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码，批量调用相对于单条调用及时性稍有延迟，验证码类型的短信推荐使用单条调用的方式
        //发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如"0085200000000"
        request.setPhoneNumbers(mobile);
        //短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //短信模板-可在短信控制台中找到
        request.setTemplateCode(template);
        //参数
        if(!CollectionUtils.isEmpty(params)){
            request.setTemplateParam(JSON.toJSONString(params));
        }

        SendSmsResponse response = null;
        try {
            IAcsClient acsClient = new DefaultAcsClient(profile);
            response = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            log.error(e.getMessage(),e);
            log.error("response-", JSON.toJSONString(response));
            throw new RuntimeException("阿里短息服务异常！");
        }

        int status = SUCCESS;
        if(!OK.equalsIgnoreCase(response.getCode())){
            status = FAIL;
        }

        if(status == FAIL){
            log.error("response-", JSON.toJSONString(response));
            throw new RuntimeException("发送失败！："+response.getMessage());
        }
    }

    @Override
    public void sendSmsList(List<LinkedHashMap<String, String>> smsList) {

    }

    public static void main(String[] args) {
        long round = Math.round(Math.random() * (9999 - 1000) + 1000);
        System.out.println(round);
    }

    public static String  genCode(){
        return ""+Math.round(Math.random() * (9999 - 1000) + 1000);
    }
}
